﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace KingOfCSharp.iHunter.UI
{
    public partial class ImagePreviewWindow : Form
    {
        private static string[] supportedExts;
        static ImagePreviewWindow()
        {
            supportedExts = new string[]
            {
                ".jpg",".jpeg",
                ".bmp",
                ".gif",
                ".png"
            };
        }
        public ImagePreviewWindow()
        {
            InitializeComponent();
        }
        public void LoadImageFile(string pathName)
        {
            this.pictureBox1.LoadAsync(pathName);
            this.Text = System.IO.Path.GetFileName(pathName);
        }

        public static bool IsFileExtensionSupported(string ext)
        {
            foreach (string supportExt in supportedExts)
            {
                if (ext.ToLowerInvariant() == supportExt)
                {
                    return true;
                }
            }
            return false;
        }

        private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
        {
            int maxHeight = 450;
            int maxWidth = 600;

            int imgHeight = pictureBox1.Image.Height;
            int imgWidth = pictureBox1.Image.Width;

            if (imgHeight <= maxHeight && imgWidth <= maxWidth)
            {
                this.Size = new Size(imgWidth, imgHeight);
            }
            else
            {
                double hRate = imgHeight / maxHeight;
                double wRate = imgWidth / maxWidth;

                double rate = hRate > wRate ? hRate : wRate;

                this.Size = new Size(
                        (int)(imgWidth / rate),
                       (int)(imgHeight / rate)
                    );
            }

            int x = this.Location.X;
            int y = this.Location.Y;

            if (x + this.Size.Width > Screen.PrimaryScreen.Bounds.Width)
            {
                x = Screen.PrimaryScreen.Bounds.Width - this.Size.Width-20;
                if (x < 0)
                    x = 0;
            }

            if (y + Size.Height > Screen.PrimaryScreen.Bounds.Height)
            {
                y = Screen.PrimaryScreen.Bounds.Height - Size.Height - 40;
                if (y <= 0)
                    y = 10;
            }

            this.Location = new Point(x, y);
        }
    }
}
